use axum::{body::Bytes, Json};
use rust_xlsxwriter::{Format, FormatAlign, Workbook};
use serde_json::{json, Value};

use crate::{ base64, code, query };
// use crate::{chrono::now_format, code, file, query, utils::host };

pub async fn create(result:Vec<Value>, group:Vec<[&str; 5]>) -> Result<Workbook, Json<Value>>{

    let bold = Format::new().set_bold().set_align(FormatAlign::Center);

    let mut workbook = Workbook::new();
    let worksheet = workbook.add_worksheet();

    let mut index = 0;
    let mut err = String::new();

    for v in group {
        let name = v[0];
        let field = v[1];
        let dtype = v[2];
        let width = v[3];
        let align = v[4];
        let mut format = Format::new().set_align(FormatAlign::Left);

        if align == "c" { format = Format::new().set_align(FormatAlign::Center) }
        
        worksheet.set_column_width(index, width.parse::<i32>().unwrap_or(15)).unwrap();

        if let Err(_) = worksheet.write_with_format(0, index, name, &bold) {
            err.insert_str(0, &format!("{}插入失败", name));
            break;
        }

        let mut i = 1;
        
        for p in &result {
            if dtype == "str" {
                if let Err(_) = worksheet.write_with_format(i, index, query::str_op(p, field)?,&format) {
                    err.insert_str(0, &format!("{}插入失败", name));
                    break;
                }
            }else if dtype == "i32"{
                if let Err(_) = worksheet.write_with_format(i, index, query::i32_op(p, field)?, &format) {
                    err.insert_str(0, &format!("{}插入失败", name));
                    break;
                }
            }
            i = i + 1;
        }

        index = index + 1;
    }

    if !err.is_empty() {
        return Err(code::sys_(err))
    }
    
    // let bys  = workbook.save_to_buffer().unwrap();
    Ok(workbook)
    
}
// 先存储文件，再访问此文件进行自动下载
/* 
pub async fn url(result:Vec<Value>, group:Vec<[&str; 5]>, name:&str) -> Result<Json<Value>, Json<Value>>{
    file::remove::remove_dir_all("/download/temp").await?;
    file::create::create_dir_all("/download/temp").await?;
    let mut workbook = create(result, group).await?;
    let path = format!("/download/temp/{}.xlsx", name.to_owned() + "_" + &now_format(3));
    match workbook.save(".".to_owned() + &path) {
        Ok(_) => {
            code::data(json!(host::get_file_host() + &path))
        },
        Err(e) => Err(code::err_(e.to_string()))
    }
}
*/
// base64下载
pub async fn base64(result:Vec<Value>, group:Vec<[&str; 5]>) -> Result<Json<Value>, Json<Value>>{
    let mut workbook = create(result, group).await?;
    match workbook.save_to_buffer() {
        Ok(f) => code::data(json!( base64::encode(f) )),
        Err(e) => code::err(e.to_string())
    }
}
// bytes下载
pub async fn bytes(result:Vec<Value>, group:Vec<[&str; 5]>) -> Result<Bytes, Json<Value>>{
    let mut workbook = create(result, group).await?;
    match workbook.save_to_buffer() {
        Ok(f) => Ok(Bytes::from(f)),
        Err(e) => Err(code::err_(e.to_string()))
    }
}